package ${rootPackage}.services.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ${rootPackage}.services.${modelClassName}Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Component;

import ${rootPackage}.models.${modelClassName};

@Component("${modelName}Service")
public class ${modelClassName}ServiceImpl implements ${modelClassName}Service {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    /**
     * Get all instances of ${modelClassName} from database
     */
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<${modelClassName}> getAll() {
        Query query = getEntityManager().createQuery("select p FROM ${modelClassName} p");
        return query.getResultList();
    }

    /**
     * Saves or updates an instance of ${modelClassName}, 
     */
    @Transactional(readOnly = false)
    public void save(${modelClassName} ${modelName}) {
        if (${modelName}.getId() == null) {
            // new
            em.persist(${modelName});
        } else {
            // update
            em.merge(${modelName});
        }
    }

    /**
     * Removes an instance of ${modelClassName} from database by Id
     */
    @Transactional(readOnly = false)
    public void remove(long id) {
        ${modelClassName} ${modelName} = get(id);
        if (${modelName} != null) {
            em.remove(${modelName});
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    /**
     * Loads an instance of ${modelClassName} from database by Id
     */
    @Transactional(readOnly = true)
    public ${modelClassName} get(long id) {
        return em.find(${modelClassName}.class, id);
    }
}
